#include "log.h"

#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <time.h>
#include <stdarg.h>


CLog::CLog()
{

}
CLog::~CLog()
{

}

bool CLog::Open(const char* cFileName)
{
	_strFileName = cFileName;
	//_iFlags = O_CREAT | O_APPEND | O_WRONLY;
	//_iMode = 00644;

	//if (_strFileName != "") {
	//	int _iFileDesc = ::open(_strFileName.c_str(),_iFlags , _iMode);
	//	if (_iFileDesc < 0)
	//		return false;
	//	else {
	//		if (_iFileDesc != -1)
	//			::close(_iFileDesc);
	//		_iFileDesc = _iFileDesc;
	//		return true;
	//	}
	//} else {
	//	return true;
	//} 

	_pfileLog = fopen(_strFileName.c_str(),"w");

	return true;
}

void CLog::Close()
{
	//if (_iFileDesc!=-1) {
	//	::close(_iFileDesc);
	//	_iFileDesc=-1;
	//}
	fclose(_pfileLog);
}

void CLog::Print(const int iLevel,const char *pcFormat,...)
{

	boost::mutex::scoped_lock lckScopedLock(_mutMutex);

	time_t timCurrent = time(NULL);
	struct tm * ptmCurrent = NULL;
#ifdef WIN32
	ptmCurrent = localtime(&timCurrent);
#else
	struct tm ptmCurrent1;
	ptmCurrent = localtime_r(&timCurrent,&ptmCurrent1);
#endif
	if( ptmCurrent )
	{
		va_list vlsList;
		va_start(vlsList,pcFormat);

		char pcFormatBuf[1024] = {0};
		_vsnprintf(pcFormatBuf, 1023, pcFormat, vlsList);

		char pcBuffer[1024] = {0};
		sprintf(pcBuffer,"%02d%02d %02d:%02d:%02d %s",
			ptmCurrent->tm_mon+1,ptmCurrent->tm_mday,
			ptmCurrent->tm_hour,ptmCurrent->tm_min,ptmCurrent->tm_sec,pcFormatBuf);

		//::write(_iFileDesc, pcBuffer,1024);
		_PrintConsole(pcBuffer,1024);
		_PrintFile(pcBuffer,1024);

		va_end(vlsList);

	}
	else
	{
		char pcBuffer[1024] = {0};
		sprintf(pcBuffer,"%02d%02d %02d:%02d:%02d Log Error",
			ptmCurrent->tm_mon+1,ptmCurrent->tm_mday,
			ptmCurrent->tm_hour,ptmCurrent->tm_min,ptmCurrent->tm_sec);

		//::write(_iFileDesc, pcBuffer,1024);

		_PrintConsole(pcBuffer,1024);
		_PrintFile(pcBuffer,1024);
	}
}

void CLog::_PrintConsole(const char *pcBuf,int iLen)
{
	printf("%s",pcBuf);
}
void CLog::_PrintFile(const char *pcBuf,int iLen)
{
	//::write(_iFileDesc, pcBuf,iLen);
	fprintf(_pfileLog,"%s",pcBuf);
	fflush(_pfileLog);
}
